﻿$(window).load(function () {
    //Show sticky help
    //$.showHelpMessage("Click on the big photo for more details|Hover mouse on the small squares at the bottom for thumbnails preview|Also click on the a small square to quickly jump to a photo|Use the top pager to see the rest of the album");
    //Pager 
    $('#album_dashboard_pager .button').mouseenter(function () {
        if (!$(this).is('.selected')) {
            $(this).stop().animate(
                {
                    opacity: 1,
                    color: '#B21822'
                },
                200
            );
        }
        else {
            $(this).stop().css('background', '#B21822').css('color', '#FFF17C');
        }
    });
    $('#album_dashboard_pager .button').mouseleave(function () {
        if (!$(this).is('.selected')) {
            $(this).stop().animate(
                {
                    opacity: 0.5,
                    color: '#FFF17C'
                },
                500
            );
        }
        else {
            $(this).stop().css('background', '#FFF17C').css('color', '#B21822');
        }
    });

    //Create the slider
    $('#slider').nivoSlider({
        effect: 'random', // Specify sets like: 'fold,fade,sliceDown'
        slices: 10, // For slice animations
        boxCols: 10, // For box animations
        boxRows: 5, // For box animations
        animSpeed: 300, // Slide transition speed
        pauseTime: 3000, // How long each slide will show
        startSlide: 0, // Set starting Slide (0 index)
        directionNav: true, // Next & Prev navigation
        directionNavHide: true, // Only show on hover
        controlNav: true, // 1,2,3... navigation
        controlNavThumbs: false, // Use thumbnails for Control Nav
        controlNavThumbsFromRel: false, // Use image rel for thumbs
        controlNavThumbsSearch: '.jpg', // Replace this with...
        controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
        keyboardNav: true, // Use left & right arrows
        pauseOnHover: true, // Stop animation while hovering
        manualAdvance: false, // Force manual transitions
        captionOpacity: 0.8, // Universal caption opacity
        prevText: 'Prev', // Prev directionNav text
        nextText: 'Next', // Next directionNav text
        beforeChange: function () { }, // Triggers before a slide transition
        afterChange: function () { }, // Triggers after a slide transition
        slideshowEnd: function () { }, // Triggers after all slides have been shown
        lastSlide: function () { }, // Triggers when last slide is shown
        afterLoad: function () {
            //Change the page message
            $('#pageMessage').html('Album loaded.').css('color', 'LightGreen');
        } // Triggers when slider has loaded
    });

    //Hide tooltip image at start
    hideLoadingThumb();

    //Show tooltip image when its loaded and hide loading text
    $('.toolTip img').load(function () {
        $(this).css('display', 'block');
        $('.toolTip .loading').css('display', 'none');
    });

    //Populate tooltip
    $('.nivo-control').each(function () {
        var thumb = $(this);
        //Mouse over show tooltip
        thumb.mouseover(function () {
            //Highlight current item
            thumb.css('background', 'black');

            //Calculate thumb index based on current page
            var rel = parseInt(thumb.attr('rel'));
            var pageString = $.getQueryStringValue('page');
            if (pageString == '') pageString = '1';
            var currentPage = parseInt(pageString);
            if (currentPage == null) currentPage = 1;
            var thumbIndex = rel + (currentPage - 1) * parseInt($(':hidden[id*=hdePageSize]').val());

            //Load the thumb image
            $('.toolTip img').attr('src', 'Album/' + $.getQueryStringValue('id') + '/Thumbnails/thumb' + thumbIndex.toString() + '.jpg');


            //Move to tool tip into position
            var cssObj = {
                'top': thumb.offset().top - 80,
                'left': thumb.offset().left - 30
            }
            $('.toolTip').css(cssObj);

            //Fade the tool tip in
            $('.toolTip').stop(true, true).fadeIn(500);
        });

        //Mouse out hide the tool tip
        $(this).mouseout(function () {
            //Hide image
            hideLoadingThumb();
            //Fade the tool tip
            $('.toolTip').stop(true, true).fadeOut(2000);

            $(this).css('background', '');
        });
    });

    //Handle photo info popup
    $('.nivo-imageLink').click(function () {
        //Block main content and show photo info popup
        $('#photo_info').dialog({
            resizable: false,
            modal: true,
            width: 320,
            height: 240,
            position: 'center',
            overlay: { backgroundColor: "#000", opacity: 0.5 },
            close: OnPhotoInfoClose,
            open: OnPhotoInfoOpen
        });

        //Stop the Slider
        $('#slider').data('nivo:vars').stop = true;

        var imgSrc = $('img', this).attr('src');
        var srcParts = imgSrc.split('/');
        var albumId = srcParts[1];
        var name = srcParts[srcParts.length - 1].split('.')[0];
        var photoId = name.substring(5, name.length);
        preparePhotoSrc(albumId, photoId);
    });

    //Handle photo info popup button click
    $('#btnPhotoInfoFullSize').click(function () {
        window.open($('#photo_info img').attr('src'));
        return false;
    });
    $('#btnPhotoInfoDownload').click(function () {
        window.location = $('#photo_info img').attr('src')+'.zip';
        return false;
    });
});

//Hide tooltip image but show loading text
function hideLoadingThumb() {
    $('.toolTip img').css('display', 'none');
    $('.toolTip .loading').css('display', 'block');
}

//Handle photo info popup closing
function OnPhotoInfoClose(e) {
    //Start the slider
    $('#slider').data('nivo:vars').stop = false;
    //Abort ajax request
    request.abort();
}

//Handle photo info popup opening
function OnPhotoInfoOpen(e) {
    //Hide the image at start, show it after loaded
    $('img', this).css('display', 'none').attr('src', '');
    $('#photo_info .buttonWrapper').css('display', 'none');
}

//Server call to prepare the source for the photo
var request = null;
function preparePhotoSrc(albumId, photoId) {
    //Cancel previous AJAX call
    if (request !== null) {
        request.abort();
    }
    var jsonData = '{"albumId":"' + albumId + '","photoId":"' + photoId + '"}';
    //Do an AJAX call to prepare the photo
    request = $.ajax({
        type: 'POST',
        url: 'Album.aspx/PrepareSourcePhoto',
        data: jsonData,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (msg) {
            //Handle error
            showPhotoError();
        },
        success: function (msg) {
            //Parse the JSON result and process
            var photo = jQuery.parseJSON(msg.d)
            //Then assign the image to the control and wait for it to load
            $('#photo_info img').attr('src', photo.url).one('load', function () {
                loadPhotoDone($(this).width(), $(this).height());
            });
        }
    });
}

//Show error
function showPhotoError() {
    $('#photo_info img').css('display', 'block');
}

//Build the image src
function loadPhotoDone(width, height) {
    //Show image
    $('#photo_info img').css('display', 'block');
    //Resiz and center the popup
    $('#photo_info').dialog({
        width: width + 32,
        height: height + 105
    }).dialog({
        position : 'center'
    });

    $('#photo_info .buttonWrapper').css('display', 'block');
}